package com.lkm.app_ui.m.Imple.fun;

import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Looper;

import com.lkm.app.event.OnDestroyActivityEvent;
import com.lkm.app.event.OnNetworkStateEvent;
import com.lkm.app.event.OnResumeActivityEvent;
import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.TaskHelp;
import com.lkm.app_ui.jz.util.JzUtil;
import com.lkm.app_ui.log.AppLogger;
import com.lkm.app_ui.m.Imple.fun.upapp.CheckUpdateUITask;
import com.lkm.app_ui.m.fun.DelegatePayTask;
import com.lkm.app_ui.m.fun.FunModule;
import com.lkm.app_ui.m.fun.OnKeyNumberEvent;
import com.lkm.app_ui.m.fun.OnPayEvent;
import com.lkm.app_ui.m.fun.OnWeightHoldEvent;
import com.lkm.app_ui.m.vip.VipInfo;
import com.lkm.app_ui.m.vip.VipModule;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.P;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.Observer;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task.ProgressData;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyarddata.SteelyardDataModule;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.m.steelyardserver.SteelyardServerModule;
import com.lkm.market2_0.m.steelyardserver.event.OnWeightInfoChangeEvent;
import com.lkm.market2_0.m.steelyardserver.to.WeightChangeInfo;
import com.lkm.market2_0.m_imple.steelyardserver.server.AbsSendWriteTask;
import com.lkm.market2_0.task.DefaultTaskExecutor;

import java.util.concurrent.atomic.AtomicReference;

public class FunModuleImple implements FunModule {


    private Handler handler;
    ApkInstall apkInstall = null;

    public FunModuleImple() {

        handler = new Handler(Looper.getMainLooper());
        regOnPayEvent();
        loopIsLock();
        regOnKeyEvent();
        reOnWeightInfoChangeEvent();
        registerReceiverOnCreateActivityEvent();

        regOnNetworkStateEvent();

        checkVersionUp();
        JzUtil.checkUpdateApp(true);

        reOnDestroyActivityEvent();
        InterceptScanInputJson.onInputContentEvent();

        apkInstall = new ApkInstall(this);
        apkInstall.installPreDownload();

        HoldNewSteelyardInfo.holdInfo();

        RegBalanceTask.waitValue();
        SaveSteelyardValue.start();

        Task task = new UpSteelyardRegTask();
        task.action();
        task.execTask();


        HoldPrintTemplateTask.start();
    }

    private OnPayEvent lastOnPayEvent;

    @Override
    public OnPayEvent lastPayInfo() {
        return lastOnPayEvent;
    }

    private void regOnPayEvent() {

        LinkBus.registerReceiver(0, new ObserverAutoNext<OnPayEvent>() {
            @Override
            public Class getBusEventClass() {
                return OnPayEvent.class;
            }

            @Override
            public void onReceiver(OnPayEvent data) {

                if (data.isSuccess()) {
                    lastOnPayEvent = data;
                }
                SteelyardDataModule steelyardDataModule = AppConst.getModuleManager().loadModule(SteelyardDataModule.class);
                if (data.isSuccess() && steelyardDataModule != null) {
                    //P.p("Bill-> FunModuleImple -> onReceiver->是否保存:" + RunTimeData.tmpPayType);
                    if (data.isSave) steelyardDataModule.saveOrderEntity(RunTimeData.steelyardInfo.getSteelyardMac(), data.getOrderEntity());
                    steelyardDataModule.clearSaleCacheInfo(RunTimeData.steelyardInfo.getSteelyardMac());
                }
            }
        });
    }


    @Override
    public void installApkIfNewDown() {
        if (apkInstall != null)
            apkInstall.installPreDownload();
    }

    @Override
    public double getCurUnitPrice() {
        return prePrice;
    }

    private int sceneFlag = 0;

    @Override
    public void setVipAble(boolean able) {

    }

    @Override
    public boolean isUserHandling() {

        return false;
    }


    @Override
    public DelegatePayTask delegatePay(OrderEntity orderEntity, String payCode, @DelegatePayTask.PayType int payType) {
        TaskHelp.cancelById(DelegatePayTaskImple.getID());
        DelegatePayTask delegatePayTask = new DelegatePayTaskImple();


        VipInfo vipInfo = null;
        try {
            vipInfo = AppConst.getModuleManager().peekModule(VipModule.class).curVipInfo();
        } catch (Exception e) {
        }

        delegatePayTask.action();
        delegatePayTask.setParam(new DelegatePayTask.DelegatePayTaskP(payCode, orderEntity, payType, vipInfo));
        delegatePayTask.execTask();
        delegatePayTask.addBackCall(delegatePayTaskBC);

        return delegatePayTask;
    }

    private BackCallAdapter<DelegatePayTask.DelegatePayTaskPR, Boolean> delegatePayTaskBC = new BackCallAdapter<DelegatePayTask.DelegatePayTaskPR, Boolean>() {

        @Override
        public void onProgresing(Task<?, DelegatePayTask.DelegatePayTaskPR, Boolean> task, ProgressData<DelegatePayTask.DelegatePayTaskPR> progressData) {
            super.onProgresing(task, progressData);

            if (progressData.getData().step == DelegatePayTask.DelegatePayTaskPR.step_content) {
            } else if (progressData.getData().step == DelegatePayTask.DelegatePayTaskPR.step_paySuccess) {

                OrderEntity orderEntity = ((DelegatePayTask) task).getParam().orderEntity;
                orderEntity.payInfo = progressData.getData().payInfo;
                LinkBus.sendBroadcast(new OnPayEvent(true, orderEntity, ((DelegatePayTask) task).getParam().vipInfo));
            } else if (progressData.getData().step == DelegatePayTask.DelegatePayTaskPR.step_payFail) {

                OrderEntity orderEntity = ((DelegatePayTask) task).getParam().orderEntity;
                orderEntity.payInfo = progressData.getData().payInfo;
                LinkBus.sendBroadcast(new OnPayEvent(false, orderEntity, ((DelegatePayTask) task).getParam().vipInfo));
            }

        }
    };


    private void loopIsLock() {
        TaskHelp.cancelById("task_loopIsLock");

        TaskAdapter<Void, Void, Void> task = new LockKeySwitchTask();
        task.set(new DefaultTaskExecutor(true), "task_loopIsLock", AppConst.getTaskManager2());
        task.action();
        task.execTask();

    }

    private double prePrice = 0;

    private void reOnWeightInfoChangeEvent() {
        LinkBus.registerReceiver(new ObserverAutoNext<OnWeightInfoChangeEvent>() {
            @Override
            public Class<OnWeightInfoChangeEvent> getBusEventClass() {
                return OnWeightInfoChangeEvent.class;
            }

            private double preweight = 0;


            @Override
            public void onReceiver(OnWeightInfoChangeEvent data) {
                WeightChangeInfo weightChangeInfo = data.getWeightChangeInfo();

                boolean isxx = false;
                if (

                        (preweight > 0 && weightChangeInfo.getWeight() <= 0)

                                || (preweight <= 0 && weightChangeInfo.getWeight() > 0)
                ) {

                    isxx = true;
                }


                if (Math.abs(preweight - weightChangeInfo.getWeight()) > 0.05) {
                    isxx = true;
                }


                if (prePrice != weightChangeInfo.getUnitPrice()) {
                    isxx = true;
                }

                if (isxx) {


                    LinkBus.sendBroadcast(new OnWeightHoldEvent(data.getSteelyardMac(), weightChangeInfo));
                }


                preweight = weightChangeInfo.getWeight();

                prePrice = weightChangeInfo.getUnitPrice();

            }
        });
    }


    private void regOnKeyEvent() {

        LinkBus.registerReceiver(new ObserverAutoNext<OnSteelyardKeyEvent>() {

            Handler handler = new Handler(Looper.getMainLooper());

            AtomicReference<String> ds = new AtomicReference<>("");

            @Override
            public Class getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }


            @Override
            public void onReceiver(OnSteelyardKeyEvent data) {


//                System.out.println("===== " + (System.currentTimeMillis() - prel));


                if (data.getKeyCode() > 10 || data.getKeyCode() < 0) {
                    return;
                }
                String d = ds.get();

                if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_DOT) {

                    if (StringHelp.isEmpty(d)) {
                        d += "0";
                    }

                    if (!d.contains("."))
                        d += ".";
                } else {
                    d += data.getKeyCode();
                }
                ds.set(d);

                handler.removeCallbacksAndMessages(null);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            OnKeyNumberEvent.sendKey(true, Float.parseFloat(ds.getAndSet("")));
                        } catch (Exception e) {
                        }

                    }
                }, 1200);
                OnKeyNumberEvent.sendKey(false, Float.parseFloat(ds.get()));

            }
        });
    }


    private void registerReceiverOnCreateActivityEvent() {
        LinkBus.registerReceiver(new Observer<OnResumeActivityEvent>() {
            @Override
            public Class<OnResumeActivityEvent> getBusEventClass() {
                return OnResumeActivityEvent.class;
            }

            @Override
            public void onReceiver(OnResumeActivityEvent data, Runnable nextRun) {
                try {
                    if (data.extActivity instanceof BaseFragmentActivity) {
                        BaseFragmentActivity activity = ((BaseFragmentActivity) data.extActivity);
                        if (activity.hasUITye(BaseFragmentActivity.UIType_NotJoinScreenLockManager))
                            return;
                    }

                } finally {
                    nextRun.run();
                }

            }
        });
    }


    private volatile boolean isLockKey = false;


    @Override
    public void setLockKeySwitch(boolean isLock_) {

        if (isLock_) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    setLockKeySwitch_(true);
                }
            });
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    setLockKeySwitch_(false);
                }
            });

        }

    }


    private void setLockKeySwitch_(boolean isLock_) {

        if (RunTimeData.isSongjian) return;

        isLockKey = isLock_;

        if (isLockKey == false) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isLockKey) {
                        return;
                    }
                    try {
                        SteelyardServerModule steelyardServerModule = AppConst.getModuleManager().loadModule(SteelyardServerModule.class);
                        AbsSendWriteTask      absSendWriteTask      = steelyardServerModule.setLockKeySwitch(RunTimeData.steelyardInfo.getSteelyardMac(), isLockKey);
                    } catch (Exception e) {
                    }

                }
            }, 800 - 200);

        } else {

            try {
                SteelyardServerModule steelyardServerModule = AppConst.getModuleManager().loadModule(SteelyardServerModule.class);
                AbsSendWriteTask      absSendWriteTask      = steelyardServerModule.setLockKeySwitch(RunTimeData.steelyardInfo.getSteelyardMac(), isLockKey);
            } catch (Exception e) {
            }
        }
    }


    private TaskAdapter<Void, Void, Void> checkVersionUp_(boolean isShowUI) {


//        new DownApkHelp(activity).downAPK(activity, "http://119.23.245.30:81/beiang/res/helper1.3.15-19-7-11-22-24.apk", Config.getApkFileCache(activity), "222k.apk");


        CheckUpdateUITask task = TaskHelp.getTask(CheckUpdateUITask.getTaskId());
        if (task != null) {
            return task;
        }

        task = new CheckUpdateUITask(isShowUI);
        task.action();
        task.setParam(null);
        task.execTask();
        return task;

    }

    @Override
    public TaskAdapter<Void, Void, Void> checkVersionUp() {
        return checkVersionUp_(false);
    }


    private void reOnDestroyActivityEvent() {

        if (RunTimeData.isXIANGCHENG)
            Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    e.printStackTrace();

                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            });

        LinkBus.registerReceiver(new ObserverAutoNext<OnDestroyActivityEvent>() {

            Handler handler = new Handler(Looper.getMainLooper());

            @Override
            public void onReceiver(OnDestroyActivityEvent data) {

                final Observer observer = this;
                if (CollectionHelp.isEmpty(BaseFragmentActivity.getActivityRuning())) {
                    handler.removeCallbacksAndMessages(null);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            if (CollectionHelp.isEmpty(BaseFragmentActivity.getActivityRuning())) {
                                LinkBus.unregisterReceiver(observer);

                                AppLogger.OnNotUIExitApp();


                                android.os.Process.killProcess(android.os.Process.myPid());

//                                new PushResetAppHandle().handler(AppConst.getApplication(),null);
                            }

                        }
                    }, 2 * 1000);
                }

            }

            @Override
            public Class getBusEventClass() {
                return OnDestroyActivityEvent.class;
            }
        });
    }


    private void regOnNetworkStateEvent() {
        LinkBus.registerReceiver(new ObserverAutoNext<OnNetworkStateEvent>() {
            @Override
            public void onReceiver(OnNetworkStateEvent data) {

                if (!data.extIsNetworkOK) return;


                if (data.extNetType != ConnectivityManager.TYPE_WIFI) {
                    AppConfig.setisUserIn4g(true);
                } else {
                    AppConfig.setisUserIn4g(false);
                }
            }

            @Override
            public Class<OnNetworkStateEvent> getBusEventClass() {
                return OnNetworkStateEvent.class;
            }
        });

    }
}